package impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import dao.BaseDao;
import dao.CommentDao;
import entity.Books;
import entity.Comment;

public class CommentImpl  extends BaseDao implements CommentDao{

	@Override
	public List<Comment> commentByBook_id(String id) {
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		String sql="SELECT * FROM comment where book_key=?";
		List<Comment> comments=new ArrayList<Comment>();
		try {
			conn=getConnection();
			pstmt=conn.prepareStatement(sql);
			pstmt.setString(1,id);
			rs=pstmt.executeQuery();
			while(rs.next()){
				Comment comment=new Comment();
				comment.setId(rs.getString("id"));
				comment.setBook_key(rs.getString("book_key"));
				comment.setCommentdate(rs.getString("commentdate"));
				comment.setMsg(rs.getString("msg"));
				comment.setName(rs.getString("name")); 
				comments.add(comment);
			}
		} catch (Exception e) {
		e.printStackTrace();
		}finally{
			closeAll(rs, pstmt, conn);
		}
		return comments;
	}

	@Override
	public int addComment(Comment comment) {
		String sql = "INSERT comment (id,book_key,commentdate,msg,name) VALUES(?,?,?,?,?)";
		Object[] objects = {comment.getId(),comment.getBook_key(),comment.getCommentdate(),comment.getMsg(),comment.getName()};
		return execeteUpdata(sql, objects);
	}

	@Override
	public int delComment(String id) {
		String sql = "delete from comment where id=?";
		Object[] objects = { id};
		return execeteUpdata(sql, objects);
	}

	@Override
	public List<Comment> commentAll() {
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		String sql="SELECT * FROM comment ";
		List<Comment> comments=new ArrayList<Comment>();
		try {
			conn=getConnection();
			pstmt=conn.prepareStatement(sql); 
			rs=pstmt.executeQuery();
			while(rs.next()){
				Comment comment=new Comment();
				comment.setId(rs.getString("id"));
				comment.setBook_key(rs.getString("book_key"));
				comment.setCommentdate(rs.getString("commentdate"));
				comment.setMsg(rs.getString("msg"));
				comment.setName(rs.getString("name")); 
				comments.add(comment);
			}
		} catch (Exception e) {
		e.printStackTrace();
		}finally{
			closeAll(rs, pstmt, conn);
		}
		return comments;
	}

}
